#include<iostream>
#include"task.hpp"
#include"ringqueue.hpp"
#include<pthread.h>


struct ThreadData
{
    ring_queue<task> *rq;
    std::string threadname;
};




void* Producer(void* args)
{
    ThreadData *td = static_cast<ThreadData*>(args);
    ring_queue<task>* rq = td->rq;
    while(true)
    {
        int x = rand() % 10;
        int y = rand() % 10;
        char op = opers[rand() % opers.size()];

        task t(x,y,op);
        rq->push(t);
        sleep(1);
    }
    
}


void* Consumer(void* args)
{
    ThreadData *td = static_cast<ThreadData*>(args);
    ring_queue<task>* rq = td->rq;
    std::string name = td->threadname;
    while(true)
    {
        task t = rq->pop();
        t();
        std::cout << t.getTask()<< std::endl;
        std::cout <<"who "<< name << "   "<<t.getResult() << std::endl;
    }
}


int main()
{
    // srand(time(nullptr));
    // pthread_t ptid,ctid;

    // ring_queue<task>* rq = new ring_queue<task>();
    // pthread_create(&ptid,nullptr,Producer,rq);
    // pthread_create(&ctid,nullptr,Consumer,rq);

    // pthread_join(ptid,nullptr);
    // pthread_join(ctid,nullptr);
    // return 0;


    srand(time(nullptr) ^ getpid());
    ring_queue<task> *rq = new ring_queue<task>(50);
    pthread_t c[5], p[3];

    for (int i = 0; i < 2; i++)
    {
        ThreadData *td = new ThreadData();
        td->rq = rq;
        td->threadname = "Productor-" + std::to_string(i);

        pthread_create(p + i, nullptr, Producer, td);
    }
    for (int i = 0; i < 3; i++)
    {
        ThreadData *td = new ThreadData();
        td->rq = rq;
        td->threadname = "Consumer-" + std::to_string(i);

        pthread_create(c + i, nullptr, Consumer, td);
    }

    for (int i = 0; i < 2; i++)
    {
        pthread_join(p[i], nullptr);
    }
    for (int i = 0; i < 3; i++)
    {
        pthread_join(c[i], nullptr);
    }

    return 0;
}